package com.zijing2333.adaptivescheduling;

import static com.zijing2333.adaptivescheduling.SwitcherManager.utils.NetworkUtil.getIP;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.textfield.TextInputEditText;
import com.zijing2333.adaptivescheduling.SwitcherManager.Switcher;
import com.zijing2333.adaptivescheduling.SwitcherManager.SwitcherService;
import com.zijing2333.adaptivescheduling.SwitcherManager.TaskInfoManager;
import com.zijing2333.adaptivescheduling.SwitcherManager.client.ClientCallback;
import com.zijing2333.adaptivescheduling.SwitcherManager.server.ServerCallback;
import com.zijing2333.adaptivescheduling.SwitcherManager.utils.ThreadUtil;

//之前把切换的功能全放在MainActivity2当中了，目前是重新创建一个MainActivity3和SwitcherService  把MainActivity2中的切换器功能移到MainActivity3当中
public class MainActivity3 extends AppCompatActivity  {
    private static final String TAG = "fun_MainActivity3";

    private StringBuffer buffer = new StringBuffer();
    //当前是否为服务端
    private boolean isServer = true;

    //Socket服务是否打开
    private boolean openSocket = false;

    //Socket服务是否连接
    private boolean connectSocket = false;

    private String ServerServiceID = "001";
    private String ClientServiceID = "001";
    private SwitcherService mSwitchService = null;

    private Switcher mSwitcher = null;


    // 定义ServiceConnection对象
    private ServiceConnection mConnection =new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            SwitcherService.MyBinder myBinder = (SwitcherService.MyBinder) iBinder; //把iBinder转换为强转为MyBinder类型
            mSwitchService = myBinder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);

        // 绑定式启动Service
        Intent intent = new Intent(this, SwitcherService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

        initView(); //进行按钮的初始化
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ChannelManager.getInstance().closeChannel();
    }

    private void initView() {
        //对应  界面中的“Ip地址”
        TextView tv_ip_address = (TextView) findViewById(R.id.tv_ip_address);
        tv_ip_address.setText("IP地址:"+getIP(this));
        RadioGroup radioGroup = (RadioGroup)findViewById(R.id.rg);
        RadioGroup radioGroup2 = (RadioGroup)findViewById(R.id.rg2); //服务端的JS列表
        RadioGroup radioGroup3 = (RadioGroup)findViewById(R.id.rg3); //客户端的JS列表
        LinearLayout lay_server = findViewById(R.id.lay_server);
        LinearLayout lay_client = findViewById(R.id.lay_client);
//        AppCompatEditText appCompatEditText = findViewById(R.id.et_msg);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_server) {
                    isServer = true;
                } else if (checkedId == R.id.rb_client){
                    isServer = false;
                }
                lay_server.setVisibility(isServer? View.VISIBLE:View.GONE);
                lay_client.setVisibility(isServer?View.GONE:View.VISIBLE);
//                appCompatEditText.setHint(isServer? "发送给客户端":"发送给服务端");
            }
        });
        radioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_Server_Js_Service1){
                    ServerServiceID = "001";
                }else if (checkedId == R.id.rb_Server_Js_Service2){
                    ServerServiceID = "002";
                }else if (checkedId == R.id.rb_Server_Js_Service3){
                    ServerServiceID = "003";
                }
            }
        });

        radioGroup3.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_Client_Js_Service1){
                    ClientServiceID = "001";
                }else if (checkedId == R.id.rb_Client_Js_Service2){
                    ClientServiceID = "002";
                }else if (checkedId == R.id.rb_Client_Js_Service3){
                    ClientServiceID = "003";
                }
            }
        });
        //开启服务/关闭服务 服务端处理
        findViewById(R.id.btn_start_service).setOnClickListener(this::startService);
        //连接服务/断开连接 客户端处理
        findViewById(R.id.btn_connect_service).setOnClickListener(this::connectService);

        //关闭客户端JS服务
        findViewById(R.id.btn_stop_client_JS).setOnClickListener(this::stopClientJs);
        //关闭服务端JS服务
        findViewById(R.id.btn_stop_server_JS).setOnClickListener(this::stopServerJs);
        //恢复服务端数据
        findViewById(R.id.btn_data_migration).setOnClickListener(this::sendDataMigration);
        //展示客户端JS服务的状态
        findViewById(R.id.btn_show_client_JS_state).setOnClickListener(this::showClinetJsState);
        //展示服务端JS服务的状态
        findViewById(R.id.btn_show_server_JS_state).setOnClickListener(this::showServerJsState);
        //数据流转 手动切换到B设备上去，代替切换的自动检测功能
        findViewById(R.id.btn_data_migration_fromServer).setOnClickListener(this::sendMigrationDataToClient);

    }

    private void sendMigrationDataToClient(View view) {
        ThreadUtil.RunInMainThread(new ThreadUtil.ThreadPram() {
            @Override
            public void Function() {
                Log.d(TAG, "点击了流转按钮-------------0");
                mSwitcher = mSwitchService.getmSwitcher(); //得到SwitchService内创建的Switcher
                String data = mSwitcher.getCurrentExecutionState(ServerServiceID);
                Log.d(TAG, "点击了流转按钮-------------1，获取到的状态值为："+data);
                ChannelManager.getInstance().sendMesToClient(ServerServiceID,"1",data);
                //迁移完成后从map中移除当前任务----思考还需不需要对端发送一个迁移完成的通知
                TaskInfoManager.getInstance().removeJsMap(ServerServiceID);
            }
        });


        //这里要进行关闭任务的操作----最好让用户点击来判断是否关闭
//        mSwitcher.stopJSExecution(ServerServiceID);
        try {
            Thread.sleep(1000);
        }catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //同时关闭任务的socket服务端
//        ChannelManager.getInstance().removeServerConnectClientThreadFromMap(ServerServiceID);
    }

    //服务端Socket开启ServerSocket
    private void startService(View view) {
        if (openSocket){
            ChannelManager.getInstance().stopServer();//思考是closeChannel还是stopServer
            openSocket=false;
        }else {
            //调用SwitcherService里面的方法来启动ServerSocket
            mSwitchService.startSocketServer();
            openSocket = true;
        }
        showInfo(openSocket?"开启Socket服务":"关闭Socket服务");
        Button btn_start_service = findViewById(R.id.btn_start_service);
        btn_start_service.setText(openSocket?"关闭Socket服务":"开启Socket服务");
    }

    //客户端连接服务端的Socket
    private void connectService(View view) {
        TextInputEditText et_ip_address = findViewById(R.id.et_ip_address);
        String ip = et_ip_address.getText().toString();
        if (ip.isEmpty()){
            showMsg("请输入Ip地址");
            return;
        }
        if (connectSocket){
            ChannelManager.getInstance().stopClient(ClientServiceID);
            connectSocket = false;
        }else {
            //调用SwitcherService里面的方法来启动客户端Socket
            mSwitchService.startSocketClient(ip,ClientServiceID);
            connectSocket = true;
        }
        showInfo(connectSocket?"连接Socket服务":"关闭Socket连接");
        Button btn_connect_service = findViewById(R.id.btn_connect_service);
        btn_connect_service.setText(connectSocket?"关闭Socket连接":"连接Socket服务");
    }

    //关闭客户端JS服务
    private void stopClientJs(View view) {
        mSwitcher = mSwitchService.getmSwitcher(); //得到SwitchService内创建的Switcher
        mSwitcher.stopJSExecution(ClientServiceID);
        Toast.makeText(getApplication(),"Service1 Stop:" ,Toast.LENGTH_SHORT).show();
    }

    //关闭服务端JS服务
    private void stopServerJs(View view) {
        mSwitcher = mSwitchService.getmSwitcher(); //得到SwitchService内创建的Switcher
        mSwitcher.stopJSExecution(ServerServiceID);
        /**ADD
         * 停止后移除map
         * */
        TaskInfoManager.getInstance().removeJsMap(ServerServiceID);
        Toast.makeText(getApplication(),"Service2 Stop:" ,Toast.LENGTH_SHORT).show();
    }

    //A设备给B设备发送流转数据
    private void sendDataMigration(View view) {
        mSwitcher = mSwitchService.getmSwitcher(); //得到SwitchService内创建的Switcher
        String data = mSwitcher.getCurrentExecutionState(ClientServiceID);
        ChannelManager.getInstance().sendMesToClient(ClientServiceID,"1",data);
        Toast.makeText(getApplication(),"Service1 save data:"+data ,Toast.LENGTH_SHORT).show();
        TaskInfoManager.getInstance().removeJsMap(ClientServiceID);
        Log.d(TAG, "流转数据发送成功----------------- ");
    }

    private void showClinetJsState(View view) {
        mSwitcher = mSwitchService.getmSwitcher(); //得到SwitchService内创建的Switcher
        Toast.makeText(getApplication(),"JS任务当前状态"+mSwitcher.getCurrentExecutionState(ClientServiceID),Toast.LENGTH_SHORT).show();
    }

    private void showServerJsState(View view) {
        mSwitcher = mSwitchService.getmSwitcher(); //得到SwitchService内创建的Switcher
        Toast.makeText(getApplication(),"JS任务当前状态"+mSwitcher.getCurrentExecutionState(ServerServiceID),Toast.LENGTH_SHORT).show();
    }

    //在信息栏中显示信息
    private void showInfo(String info) {
        buffer.append(info).append("\n");
        TextView tv_info = findViewById(R.id.tv_info);
        ThreadUtil.RunInMainThread(new ThreadUtil.ThreadPram()
        {
            @Override
            public void Function()
            {
                tv_info.setText(buffer.toString());
            }
        });
    }
    //在主线程的底部显示提示信息，2s的提示
    private void showMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

}